package com.fly.feishu.infrastructure.config;

import org.apache.http.client.HttpClient;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestemplateConfig {
    /**
     * RestTemplate
     *
     * @return
     */
    @Bean
    public static RestTemplate restTemplate() {
//        return new RestTemplateBuilder()
//                .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(
//                        HttpClientBuilder.create().useSystemProperties().setRedirectStrategy(new LaxRedirectStrategy()).build()))
//                .build();

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());
        connectionManager.setDefaultMaxPerRoute(20);
        connectionManager.setMaxTotal(2000); // 总的最大连接数


        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(5000);
        httpRequestFactory.setConnectTimeout(10000);
        httpRequestFactory.setReadTimeout(72000);

        HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).setRedirectStrategy(new LaxRedirectStrategy()).build();
        httpRequestFactory.setHttpClient(httpClient);

        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        return restTemplate;

    }
}
